import { task } from 'gulp';
import * as path from 'path';
import * as fs from 'fs';
import { srcPath, autoPath } from '../../config';

const buildUtil = require('../../../../scripts/buildUtils.js');

class ColorProperty {
  name: string;
  value?: string;

  constructor(name: string) {
    this.name = name;
  }
}

class ColorVariable {
  name: string;
  property: string;
  value?: string;

  constructor(name: string, property: string) {
    this.name = name;
    this.property = property;
  }
}

task('genColors', (done) => {
  // Extract custome properties from any theme file
  const propertyFilePath = path.join(srcPath, './styles/themes/white.scss');
  const propertyFileCss = buildUtil.buildSass(null, propertyFilePath);
  const colorProperties = propertyFileCss.match(/\-\-fui\-[a-z0-9\-]+/g).map((property) => new ColorProperty(property));

  // Extract variables with color from the file
  const variableFilePath = path.join(srcPath, './styles/variables.sass');
  const variableFileContent = fs.readFileSync(variableFilePath, 'utf8');
  const variableFileLines = variableFileContent.split('\n');
  const variables: string[] = variableFileLines.reduce((ret, line) => {
    const variableMatch = line.match(/^\$[a-z0-9\-]+/);
    const variableValueMatch = line.match(/fui-color\(/g);
    if (variableMatch && variableValueMatch) {
      (ret as Array<string>).push(...variableMatch);
    }
    return ret;
  }, []);

  // Use variable and compile, get the compiled value
  const variablesUsageFile = variableFileContent + '\n.variables\n' + variables.reduce((ret, variable) => {
    ret += `  ${variable.replace('$', '')}: ${variable}\n`;
    return ret;
  }, '');
  const variablesCompiledFile = buildUtil.buildSass(variablesUsageFile, null, true);
  const variablesCompiledFileLines = variablesCompiledFile.split('\n').slice(1, -1);
  const colorVariables: ColorVariable[] = variablesCompiledFileLines.reduce((ret, line) => {
    const lineParts = line.split(':');
    const variableNameMatch = lineParts[0].match(/[a-z0-9\-]+/);
    const variablePropertyMatch = lineParts[1].match(/\-\-fui\-[a-z0-9\-]+/);
    if (variableNameMatch && variablePropertyMatch) {
      ret.push(new ColorVariable('$' + variableNameMatch[0], variablePropertyMatch[0]));
    }
    return ret;
  }, []);

  fs.writeFileSync(path.join(autoPath, 'color-properties.ts'), `export default ${JSON.stringify(colorProperties, null, 2)};`);
  fs.writeFileSync(path.join(autoPath, 'color-variables.ts'), `export default ${JSON.stringify(colorVariables, null, 2)};`);
  done();
});
